﻿using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackExchange.Redis
{
    public static class TypedStringExtensionMethods
    {

        public static bool StringSet<TEntity>(this IDatabase database, RedisKey key, TEntity item, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags flags = CommandFlags.None)
        {
            var value = JsonSerializer.SerializeToString(item);
            return database.StringSet(key, value, expiry, when, flags);
        }

        public static TEntity StringGetSet<TEntity>(this IDatabase database, RedisKey key, TEntity item, CommandFlags flags = CommandFlags.None)
        {
            var value = JsonSerializer.SerializeToString(item);
            var oldValue = database.StringGetSet(key, value, flags);
            if (oldValue.HasValue)
            {
                return JsonSerializer.DeserializeFromString<TEntity>(oldValue);
            }
            else
            {
                return default(TEntity);
            }
        }

        public static TEntity StringGet<TEntity>(this IDatabase database, RedisKey key, CommandFlags flags = CommandFlags.None)
        {
            var value = database.StringGet(key, flags);
            if (value.HasValue)
            {
                return JsonSerializer.DeserializeFromString<TEntity>(value);
            }
            else
            {
                return default(TEntity);
            }
        }


        public static TEntity[] StringGet<TEntity>(this IDatabase database, RedisKey[] keys, CommandFlags flags = CommandFlags.None)
        {
            var values = database.StringGet(keys, flags);
            TEntity[] items = new TEntity[values.Length];
            for (int i = 0; i < values.Length; i++)
            {
                var value = values[i];
                if (value.HasValue)
                {
                    items[i] = JsonSerializer.DeserializeFromString<TEntity>(value);
                }
                else
                {
                    items[i] = default(TEntity);
                }
            }
            return items;
        }
    }
}
